package com.dg11185.nearshop.activity.shop;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.android.nearshop.R;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.ormlite.android.apptools.OpenHelperManager;
import com.dg11185.libs.ormlite.dao.Dao;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.activity.shop.ShopFragment.ListState;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.StaticData;
import com.dg11185.nearshop.baidumap.MyMapLocation;
import com.dg11185.nearshop.baidumap.MyMapLocation.MyBDLocationListener;
import com.dg11185.nearshop.dbHelper.OrmLiteHelper;
import com.dg11185.nearshop.net.CacheConstant;
import com.dg11185.nearshop.net.NetCacheClient;
import com.dg11185.nearshop.net.entity.Area;
import com.dg11185.nearshop.net.entity.Industry;
import com.dg11185.nearshop.net.entity.MerchantItem;
import com.dg11185.nearshop.net.request.GetMerchantListRequest;
import com.dg11185.nearshop.net.response.GetMerchantListResponse;
import com.dg11185.nearshop.net.response.NetStatus;
import com.dg11185.nearshop.view.adapter.ShopMainAdapter;
import com.dg11185.nearshop.view.xlistview.XListView;
import com.dg11185.nearshop.view.xlistview.XListView.IXListViewListener;
import com.wlper.lib.uitls.ViewUtils;
import com.wlper.lib.view.loading.BaseLoadLayout.LoadStateHandler;
import com.wlper.lib.view.loading.LoadLayoutWithTweenAnim;

/**
 * 
 * @author：Daibo
 * @time：2014-6-25 下午2:59:19
 */
public class ShopListActivity extends SubPageActivity implements IXListViewListener {

    public final static int BRAND_LIST = 1;

    public final static int SEARCH_LIST = 2;

    private final static int PAGE_SIZE = 10;

    private int total = 0;

    private int pageNo = 1;

    private int cur_tag = 1;

    private ListState listState = ListState.INIT;

    private XListView listView = null;

    private ShopMainAdapter listAdapter = null;

    private List<MerchantItem> listDatas = null;

    private GetMerchantListRequest request = null;

    private LocationClient locationClient = null;

    /** 数据库 */
    private OrmLiteHelper databaseHelper = null;// 底包数据库helper

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_favor);
        listView = (XListView) this.findViewById(R.id.user_favor_list);
        listDatas = new ArrayList<MerchantItem>();
        listAdapter = new ShopMainAdapter(this, listDatas);
        listView.setAdapter(listAdapter);
        listView.setXListViewListener(this);

        request = new GetMerchantListRequest(Constants.AREA_NUM);
        if (getIntent().getExtras().getInt("tag") == BRAND_LIST) {
            setSubPageTitle(getIntent().getExtras().getString("title"));
            request.add("brandId", getIntent().getExtras().getString("brandId"));
        } else {
            cur_tag = SEARCH_LIST;
            setSubPageTitle(getIntent().getExtras().getString("merchantName"));
            request.add("merchantName", getIntent().getExtras().getString("merchantName"));
        }
        if (MyMapLocation.location != null) {
            listAdapter.setLocation(MyMapLocation.location);
        } else {
            initLocationData();
        }
        initDBData();
        initListDatas();
    }

    @Override
    protected void onDestroy() {

        // 注销定位
        if (locationClient != null) {
            locationClient.stop();
        }
        super.onDestroy();
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }
    }

    /**
     * You'll need this in your class to get the helper from the manager once
     * per class.
     */
    private OrmLiteHelper getHelper() {
        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(this, OrmLiteHelper.class);
        }
        return databaseHelper;
    }

    private void initDBData() {
        Dao<Industry, Integer> industryDao = getHelper().getIndustryDao();
        Dao<Area, Integer> areaDao = getHelper().getAreaDao();
        try {
            List<Industry> industries = industryDao.queryForAll();
            List<Area> areas = areaDao.queryForAll();
            Map<String, String> industryMap = new HashMap<String, String>();
            Map<String, String> areaMap = new HashMap<String, String>();

            for (Industry i : industries) {
                industryMap.put(i.name, i.industryId);
            }
            for (Area a : areas) {
                areaMap.put(a.name, a.areaNum);
            }

            if (cur_tag == BRAND_LIST) {
                String areaName = StaticData.AREA_NAME;
                if (areaName != null && !"".equals(areaName) && !"全城".equals(areaName)) {
                    request.add("areaNum", areaMap.get(areaName));
                }
            }
            listAdapter.setAreaMap(areaMap);
            listAdapter.setIndustryMap(industryMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private void initLocationData() {

        locationClient = new LocationClient(mActivity);
        MyMapLocation mapLocation = new MyMapLocation(this, new MyBDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bDLocation) {
                listAdapter.setLocation(bDLocation);
                listAdapter.notifyDataSetChanged();
            }
        });
        mapLocation.start();
    }

    private void initListDatas() {
        final LoadLayoutWithTweenAnim loadingView = (LoadLayoutWithTweenAnim) this
                .findViewById(R.id.user_favor_loading);
        loadingView.setStateHandler(new LoadStateListener());
        if (listState == ListState.INIT) {
            loadingView.onLoading();
        }
        if (request != null) {
            request.getParams().remove("chshSign");
        }
        request.add("pageNumber", pageNo + "").add("pageSize", PAGE_SIZE + "").encryption();
        request.setActionListener(new GetMerchantListRequest.ActionListener<GetMerchantListResponse>() {

            @Override
            public void onSuccess(GetMerchantListResponse result) {
                if (NetStatus.SUCCESS == result.status) {
                    total = Integer.parseInt(result.total);
                    if (pageNo * PAGE_SIZE >= total) {
                        listView.setPullLoadEnable(false);
                    } else {
                        listView.setPullLoadEnable(true);
                    }
                    if (total == 0 && listState == ListState.INIT) {
                        loadingView.onNoData();
                        listView.setVisibility(View.INVISIBLE);

                    } else {
                        if (listState == ListState.REFRESH) {
                            listDatas.clear();
                        }
                        listView.setVisibility(View.VISIBLE);
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        loadingView.onLoadSuccess();
                        listDatas.addAll(result.merchants);
                        listAdapter.notifyDataSetChanged();
                    }
                } else {
                    onFailure(-1);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                listView.stopLoadMore();
                listView.stopRefresh();
                loadingView.onLoadFailed();
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    loadingView.setLoadFailedHint("网络连接错误，连接之后点击重试!");
                } else if (resultCode == -1) {
                    loadingView.setLoadFailedHint("服务器连接失败!");
                }
            }
        });
        NetCacheClient.httpCacheGet(request);
    }

    private Handler handler = new Handler();

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                CacheConstant.deleteCacheFolder(Constants.getMerchantList);
                pageNo = 1;
                listState = ListState.REFRESH;
                initListDatas();
            }
        }, 500);

    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                if (PAGE_SIZE * pageNo > total) {
                    ViewUtils.showToast(ShopListActivity.this, R.string.no_data_anymore);
                    listView.stopLoadMore();
                }
                pageNo++;
                listState = ListState.LOAD_MORE;
                initListDatas();
            }
        }, 500);

    }

    private class LoadStateListener implements LoadStateHandler {

        @Override
        public void onLoading() {
        }

        @Override
        public void onLoadFailed() {
        }

        @Override
        public void onLoadSuccess() {
        }

        @Override
        public void onReload() {
            listState = ListState.INIT;
            initListDatas();
        }

    }
}
